package com.sqm.conntroller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.sqm.entity.Result;
import com.sqm.entity.User;
import com.sqm.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

/**
 * 功能: 用户类
 * 作者: 沙琪马
 * 日期: 2024/5/21 16:43
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    UserService userService;

    /**
     * 新增用户信息
     *
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        try {
            if (StrUtil.isBlank(user.getName())){
                user.setName("小可爱"+ RandomUtil.randomNumbers(4));
            }
            if (StrUtil.isBlank(user.getPassword())){
                user.setPassword("123"); // 默认密码 ：123
            }
            if (StrUtil.isBlank(user.getRole())){
                user.setRole("用户"); // 默认角色 ：用户
            }
            userService.saveOrUpdate(user);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                return Result.error("插入数据错误");
            } else {
                return Result.error("系统错误");
            }
        }
        return Result.success();
    }

    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        userService.updateById(user);
        return Result.success();
    }


    /**
     * 批量导出数据
     */
    @GetMapping("/export")
    public void exportData(@RequestParam(required = false) String username,
                           @RequestParam(required = false) String name,
                           @RequestParam(required = false) String ids, // get 请求不能直接接收list类型的数据
                           HttpServletResponse response) throws IOException {
        ExcelWriter writer = ExcelUtil.getWriter(true);

        List<User> list;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(ids)) {
            // 第一种情况
            List<Integer> idsArr1 = Arrays.stream(ids.split(",")).map(Integer::valueOf).toList();
            queryWrapper.in("id", idsArr1);
        } else {
            //第二种情况, 全部导出或者条件导出

            queryWrapper.like(StrUtil.isNotBlank(username), "username", username);
            queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        }

        list = userService.list(queryWrapper); // 查询出当前user表的所有数据
        writer.write(list,true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        // URLEncoder.encode() 中文编码
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("用户信息表", "UTF-8") + ".xlsx");
        ServletOutputStream outputStream = response.getOutputStream(); // 输出流对象
        writer.flush(outputStream, true);
        writer.close();
        outputStream.flush();
        outputStream.close();

    }

    /**
     * 批量导入
     * @param file
     * @return
     */
    @PostMapping("/import")
    public Result importData(MultipartFile file) throws IOException {
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        List<User> users = reader.readAll(User.class);
        // 写入到数据到数据库
        try {
            userService.saveBatch(users);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("数据批量导入出错");
        }
        return Result.success();
    }
}
